package com.fitness.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fitness.model.Order;
import com.fitness.model.WxInformation;
import com.fitness.service.WxService;
import com.fitness.util.JsonUtil;
import com.fitness.util.MyConfig;
import com.google.gson.Gson;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@Controller
public class WxController {

	@Autowired
	WxService wxService;
	
	//获取openid 重定向接口
		@RequestMapping(value="wx/getopenid",produces="application/json;charset=utf-8")
		public void wxopenid(HttpServletResponse response){
			try {
				response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbb9dc8b31a2e5278&redirect_uri=http://192.168.99.117:8080/fitnessclass/wx/openid&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	
	/**
	 * 获取openid的接口
	 * @param code
	 * 暂时更新掉
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping(value="wx/openid",produces="application/json;charset=utf-8")
	public String wxopenid(String code,HttpServletResponse response) throws IOException{
		MyConfig config = new MyConfig();
		//调用http请求 获取一个openid access_token
		//String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxb854524da13cb332&secret=8575b5adf9c13f2b6b9ae0c8bf2ca821&code="+code+"&grant_type=authorization_code";
		String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+config.getAppID()+"&secret=8575b5adf9c13f2b6b9ae0c8bf2ca821&code="+code+"&grant_type=authorization_code";
		OkHttpClient oc = new OkHttpClient();//创建okhttp对象
		//创建请求对象
		Request okrequest = new Request.Builder().url(url).build();
		String str = "";
		Map<String, Object> map = null;
		try {
			Response  okresponse = oc.newCall(okrequest).execute();
			str = okresponse.body().string();
			Gson gson = new Gson();
			map = gson.fromJson(str, HashMap.class);
			System.out.println("map==============================="+map);
			System.out.println();
			String openid = (String) map.get("openid");
			System.out.println("openid+++++++++++++++++++++++++++++++++"+openid);
			if(map.containsKey("errcode")) {
				JsonUtil ju = new JsonUtil();
				ju.setErrorCode(400);
				ju.setSuccess(false);
				ju.setMsg("获取openid失败，请查询errorCode信息");
				return ju.getJson();
			}
			if (openid!=null || !openid.equals("")) {
				
				WxInformation wxInformation = new WxInformation();
				wxInformation.setOpenid(openid);
				//判断openid是否存在数据库  如果存在 return success  不存在存入数据库
				Integer count = wxService.isInOpenid(wxInformation);
				
				if (count==0) {
					//openid存入数据库
					wxService.insertOpenid(wxInformation);
				}else {
					JsonUtil ju = new JsonUtil();
					ju.setSuccess(true);
					ju.add(map);
					ju.setMsg("获取openid成功");
					return ju.getJson();
			}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
			return JsonUtil.blank(false,400, "服务器请求错误");
		}
		JsonUtil ju = new JsonUtil();
		ju.add(map);
		ju.setMsg("获取openid成功");
		if(map.containsKey("errcode")) {
			ju.setErrorCode(400);
			ju.setSuccess(false);
			ju.setMsg("获取openid失败，请查询errorCode信息");
		}
		System.out.println("--------------------"+ju.getJson());
		return ju.getJson();
	}

	/**
	 * 调用微信h5支付接口
	 * @param order
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="wx/pay/sign",produces="application/json;charset=utf-8")
	public String osPaySign(Order order,HttpServletRequest request,HttpServletResponse response) throws Exception {
		String str = wxService.WxPaySign(order,request);
		return str;
	}
	
	
	
		//微信支付h5回调
		@RequestMapping(value="wx/h5/back",produces="application/xml;charset=utf-8")
		public String payBack(HttpServletRequest request,HttpServletResponse response) throws Exception{
			String xml = wxService.wxH5PayBack(request);
			return xml;
		}
		
		
}
